package com.lishe.lishe.lishe.module.myorder.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.AddressObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.module.me.activity.AddressManageActivity;
import com.lishe.lishe.lishe.module.myorder.bean.BusinessObject;
import com.lishe.lishe.lishe.module.myorder.bean.GoodObject;
import com.lishe.lishe.lishe.module.myorder.bean.OrderObject;
import com.lishe.lishe.lishe.module.myorder.http.HttpMyOrder;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.module.shopingcart.http.HttpShopppingCart;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/9/11.
 * 确认订单
 */

public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener {

    private TextView texTitltle;
    private TextView texName;
    private TextView texPhone;
    private TextView texAddress;
    private TextView texGoodsCount;
    private TextView texmoney;
    private TextView texIntegral;
    private Button btnSubmit;
    private Button btnBack;
    private LinearLayout contentLayout;
    private LinearLayout addressLayout;

    private OrderObject orderObject;//订单对象
    private AddressObject addressObject;//地址对象

    private ImageLoaderUtils imageLoaderUtils;
    private String token;

    public static void jump(Activity activity, OrderObject orderObject, AddressObject addressObject) {
        Intent intent = new Intent(activity, ConfirmOrderActivity.class);
        intent.putExtra("orderObject", orderObject);
        intent.putExtra("addressObject", addressObject);
        activity.startActivity(intent);
    }

    public static void jumpForResult(Activity activity, OrderObject orderObject, AddressObject addressObject, int requstCode) {
        Intent intent = new Intent(activity, ConfirmOrderActivity.class);
        intent.putExtra("orderObject", orderObject);
        intent.putExtra("addressObject", addressObject);
        activity.startActivityForResult(intent, requstCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        token = Globals.getToken();
        orderObject = (OrderObject) getIntent().getSerializableExtra("orderObject");
        addressObject = (AddressObject) getIntent().getSerializableExtra("addressObject");
        regisBrocastReciver();
        setContentView(R.layout.activity_confirm_order);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver!=null){
            unregisterReceiver(receiver);
            receiver=null;
        }
    }

    private void initView() {
        texTitltle = findViewById(R.id.title_text_title);
        texName = findViewById(R.id.name);
        texPhone = findViewById(R.id.phone);
        texAddress = findViewById(R.id.address);
        texGoodsCount = findViewById(R.id.goods_count);
        texmoney = findViewById(R.id.money);
        btnBack = findViewById(R.id.title_left_button);
        contentLayout = findViewById(R.id.centent_layout);
        addressLayout = findViewById(R.id.address_layout);
        texIntegral = findViewById(R.id.integral);
        btnSubmit = findViewById(R.id.submit);
        initData();
        setlistener();
    }

    /**
     * 数据初始化
     */
    private void initData() {
        try {
            imageLoaderUtils = new ImageLoaderUtils();
            texTitltle.setText(getString(R.string.confirm_order));
            if (addressObject != null) {
                texName.setText(addressObject.getName());
                texPhone.setText(addressObject.getMobile());
                texAddress.setText(addressObject.getArea() + addressObject.getAddr());
            }
            if (orderObject != null) {
                Log.e("orderObject", "no_null");
                contentLayout.removeAllViews();
//                orderObject.setMoney(0);

                texIntegral.setText(String.format(getString(R.string.input_integral1), String.format("%.0f", (orderObject.getMoney() * 100))));
                for (BusinessObject business : orderObject.getTrade_paybillData()) {
                    View businessLayout = getLayoutInflater().inflate(R.layout.item_business_layout, null);
                    LinearLayout goods_layout = businessLayout.findViewById(R.id.goods_layout);
                    TextView texDeliveryMode = businessLayout.findViewById(R.id.delivery_mode);
                    TextView business_name = businessLayout.findViewById(R.id.business_name);
                    TextView goods_count = businessLayout.findViewById(R.id.goods_count);
                    TextView money = businessLayout.findViewById(R.id.money);
                    if (business.getTradeData().getPost_fee() != 0) {
                        texDeliveryMode.setText("邮寄费:" + business.getTradeData().getPost_fee()+"元");
                    } else {
                        texDeliveryMode.setText(getString(R.string.free));
                    }
                    business_name.setText(business.getTradeData().getShopName());
                    goods_count.setText(getString(R.string.total_count_integral1, business.getTradeData().getOrderList().size() + ""));
                    Log.e("当前金额", business.getPayment() + "");
                    money.setText(String.format("%.0f", (business.getPayment() * 100)));
                    goods_layout.removeAllViews();
                    for (final GoodObject goods : business.getTradeData().getOrderList()) {
                        Log.e("orderObject", "商品" + business.getTradeData().getOrderList().size());
                        View goodsLayout = getLayoutInflater().inflate(R.layout.item_order_adapter_business_good, null);
                        ImageView goodsImg = goodsLayout.findViewById(R.id.goods_img);
                        TextView goodsDescribe = goodsLayout.findViewById(R.id.goods_describe);
                        TextView goodsFormat = goodsLayout.findViewById(R.id.goods_format);
                        TextView goodsPrice = goodsLayout.findViewById(R.id.goods_price);
                        TextView goodsCount = goodsLayout.findViewById(R.id.goods_count);
                        goodsCount.setText("x" + goods.getNum());
                        goodsDescribe.setText(goods.getTitle());
                        goodsFormat.setText(goods.getSpec_info());
                        goodsPrice.setText((int) (goods.getPrice() * 100) + "");
                        imageLoaderUtils.displayImage(goods.getPic_path(), goodsImg);
                        goodsLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                MallGoodsActivity.jump(ConfirmOrderActivity.this, goods.getItem_id());
                            }
                        });
                        goods_layout.addView(goodsLayout);
                    }
                    contentLayout.addView(businessLayout);
                }
            } else {
                Log.e("orderObject", "null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setlistener() {
        btnBack.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        addressLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.submit:
                createOrrderFinish();
                break;
            case R.id.address_layout:
                AddressManageActivity.jump(ConfirmOrderActivity.this);
        }
    }

    /**
     * 获取默认收货地址
     */
    private void getReceiveAddress() {
        HttpShopppingCart.getReceiveAddress(token, getAddressRespose);
    }

    /**
     * 地址接口监听
     */
    AsyncHttpResponseHandler getAddressRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e("收货地址", result);
            try {
                JSONObject json = new JSONObject(result);
                boolean isNull = true;//地址是否为空
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONArray dataArray = json.optJSONArray("data");
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject addressJson = dataArray.optJSONObject(i);
                        String address = addressJson.optString("def_addr");
                        if (!"1".equals(address)) {
                            continue;
                        } else {
                            isNull = false;
                            addressObject.setAddr(addressJson.optString("addr"));
                            addressObject.setAddr_id(addressJson.optString("addr_id"));
                            addressObject.setArea(addressJson.optString("area"));
                            addressObject.setArea_id(addressJson.optString("area_id"));
                            addressObject.setDef_addr(addressJson.optString("def_addr"));
                            addressObject.setMobile(addressJson.optString("mobile"));
                            addressObject.setName(addressJson.optString("name"));
                            addressObject.setUser_id(addressJson.optString("user_id"));
                            addressObject.setZip(addressJson.optString("zip"));
                            Log.e("收货地址", addressObject.getArea() + addressObject.getAddr());
//                            texAddress.setText(addressObject.getArea() + addressObject.getAddr());
                            initData();
                            return;
                        }
                    }
                    if (isNull) {
                        texAddress.setHint("请选择地址...");
                    } else {
                        texAddress.setText(addressObject.getArea() + addressObject.getAddr());
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    };

    /**
     * 确认订单
     */
    private void createOrrderFinish() {
        if (orderObject != null) {
            LoadingUtils.createLoadingDialog(this, "确认订单中...", true);
            HttpMyOrder.createOrderFinish(token, orderObject.getRemarks(),
                    orderObject.getShopIds(), orderObject.getItemIds(), orderObject.getDlytmplIds(),
                    orderObject.getPostFees(), orderObject.getSkuIds(), orderObject.getCarIds(), createGoodsFinishRespose);
        } else {
            toast("没有订单或订单异常！");
        }
    }

    /**
     * 确认订单监听
     */
    AsyncHttpResponseHandler createGoodsFinishRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e("生成订单finish", result);
            LoadingUtils.closeDialog();
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    String paymentId = dataObject.optString("paymentId");
                    String time = dataObject.optString("created_time");
                    orderObject.setPayment_id(paymentId);
                    orderObject.setCreated_time(time);
                    PayActivity.jump(ConfirmOrderActivity.this, orderObject, Globals.REQUSE_CODE_PayActivity);
                    sendbrodcasToShoppingCart();
                    finish();
                } else {
                    LoadingUtils.closeDialog();
                    String msg = json.optString("msg");
                    toast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            toast("网络或服务器异常！");
        }
    };

    //-----------------------------选择地址广播处理-----------------------------
    private void regisBrocastReciver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Globals.ACTION_UPADDRESS);
        registerReceiver(receiver, intentFilter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Globals.ACTION_UPADDRESS)) {
                Log.e("收到广播", "更新UI");
                getReceiveAddress();
            }
        }
    };

    /**
     * 发送广播更新UI
     */
    private void sendbrodcasToShoppingCart() {
        Intent intent = new Intent();
        intent.setAction(Globals.ACTION_UP_UI);
        intent.putExtra("isToast", false);
        sendBroadcast(intent);
    }
}
